/**
 * gpms
 * 2012-12-24 下午3:44:37
 * 作者：陈志明
 * 
 */
package com.gpms.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

/**
 * @author Jackie chen
 *
 */
public class ListForJson {
	
	/**
	 * 
	 * @param page
	 * @param totalRows
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public static String doListJson(int page,int totalRows,List list) throws Exception{
		StringBuffer str=new StringBuffer();
		str.append("{\"pager.pageNo\":"+page+",\"pager.totalRows\":"+totalRows+",\"rows\":");
		if(list!=null&&list.size()>0){
			str.append("[");
			int i=0;
			for (Object obj:list){
				i++;
				doSpecialSign(obj);
				str.append("{");
				str.append(getJsonstrFromdto(obj));
				str.append("}");
				if (i < list.size())
					str.append(",");
			}
			str.append("]");
		}else {
			str.append("[]}");
		}
		return str.toString();
	}
	
	
	public static void doSpecialSign(Object obj) throws Exception {
		Field field[] = obj.getClass().getDeclaredFields();
		for (Field target : field) {
			if (target.getType() != String.class)
				continue;
			String value = BeanUtils.getProperty(obj, target.getName());
			if (value != null)
				value = value.replace("\r\n", "<br>");
			BeanUtils
					.setProperty(obj, target.getName(), dealString4JSON(value));
		}
	}
	
	public static String dealString4JSON(String ors) {
		ors = ors == null ? "" : ors;
		StringBuffer buffer = new StringBuffer(ors);
		int i = 0;
		while (i < buffer.length()) {
			if (buffer.charAt(i) == '\'' || buffer.charAt(i) == '\\') {
				buffer.insert(i, '\\');
				i += 2;
			} else {
				i++;
			}
		}
		String tmpstr = buffer.toString().replaceAll("\r\n", "<br/>");
		return tmpstr.replaceAll("\n", "<br/>");
	}
	
	public static String getJsonstrFromdto(Object obj) throws Exception {
		StringBuffer sb = new StringBuffer();

		Field fields[] = obj.getClass().getDeclaredFields();
		for (Field target : fields) {
			if (1 != 1)// target.getType().getSuperclass()==DtoSupport.class
						// 自己修改
			{
				String fieldName = target.getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase();

				String getMethodName = "get" + firstLetter
						+ fieldName.substring(1);
				Method method = obj.getClass().getMethod(getMethodName, null);
				Object propertyobj = method.invoke(obj, null);
				if (propertyobj != null)
					sb.append(",\"" + target.getName() + "\":{"
							+ getJsonstrFromdto(propertyobj) + "}");
			} else {
				String value = BeanUtils.getProperty(obj, target.getName());
				if (value == null || "null".equals(value))
					value = "";
				sb.append(",\"" + target.getName() + "\":\""
						+ dealString4JSON(value) + "\"");
			}
		}
		return sb.toString().substring(1);

	}
}
